package com.hnhy.bluetooth.adapter

import android.bluetooth.BluetoothGattCharacteristic
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hnhy.bluetooth.ble.BleUtils
import com.hnhy.bluetooth.databinding.ItemCharacteristicBinding

class CharacteristicAdapter(
    private val characteristic: List<BluetoothGattCharacteristic>,
    private val operateCallback: OperateCallback
) : RecyclerView.Adapter<CharacteristicAdapter.ViewHolder>(){

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(ItemCharacteristicBinding.inflate(LayoutInflater.from(parent.context), parent, false))
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.binding.tvCharacterName.text = BleUtils.getCharacteristicsName(characteristic[position].uuid)
        holder.binding.tvCharacterUuid.text = BleUtils.getShortUUID(characteristic[position].uuid)
        //加载特性属性
        holder.binding.rvProperty.apply {
            layoutManager = LinearLayoutManager(context).apply {
                orientation = LinearLayoutManager.HORIZONTAL
            }
            val properties: List<String> = BleUtils.getProperties(characteristic[position].properties)
            adapter = PropertyAdapter(properties, object : OnItemClickListener{
                //点击属性
                override fun onItemClick(view: View, position: Int) {
                    operateCallback.onPropertyOperate(characteristic[position], properties[position])
                }
            })
        }
    }

    override fun getItemCount() = if (characteristic.size > 0) characteristic.size else 0

    class ViewHolder(itemView: ItemCharacteristicBinding) : RecyclerView.ViewHolder(itemView.root){
        val binding: ItemCharacteristicBinding
        init {
            binding = itemView
        }
    }

}